import json
import datetime
import logging
logger = logging.getLogger('django')
from django.http import JsonResponse,request
from django.views import View
from hourses.models import House
from ihome.utils.views import LoginRequiredMixin
from orders.models import Order
from django.db import transaction


# 添加订单
class AddOrderView(LoginRequiredMixin,View):
    '''添加订单'''
    def post(self,request):
        """
            下单
            1. 获取参数
            2. 校验参数
            3. 查询指定房屋是否存在
            4. 判断当前房屋的房主是否是登录用户
            5. 查询当前预订时间是否存在冲突
            6. 生成订单模型，进行下单
            7. 返回下单结果
        """

        # 获取用户
        user = request.user
        # 1.获取传入的参数
        dict = json.loads(request.body.decode())
        house_id = dict.get('house_id')
        start_date = dict.get('start_date')
        end_date = dict.get('end_date')

        # 2.校验参数
        if not all([house_id, start_date, end_date]):
            return JsonResponse({'errno': 4103,
                                 'errmsg': '参数不齐'})

        try:
            start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d')
            end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')
            assert start_date < end_date, Exception("开始日期大于结束日期")
            # 计算入住天数
            days = end_date - start_date
            day = int(days.days)
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4103,
                                 'errmsg': "参数错误"})
        # 3.查询指定房屋是否存在
        try:
            house = House.objects.get(id=house_id)
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4002,
                                 'errmsg': "房屋不存在"})


        # 4.判断当前房屋的房主是否是当前用户，如果当前用户是房东，不能预订
        if house.user_id == user.id:
            return JsonResponse({'errno': 4105,
                                 'errmsg': "不能预订自已的房屋"})

        # 5.查询该房屋是否有订单冲突
        try:
            count = Order.objects.filter(house_id=house_id, begin_date__lt=end_date, end_date__gt=start_date,status=0).count()
        except Exception as e:
            return JsonResponse({'errno': 4302,
                                 'errmsg': "读取失败"})
        if count > 0:
            return JsonResponse({'errno': 4004,
                                 'errmsg': "该房屋已被预订"})
        # 6.生成订单模型，进行下单

        with transaction.atomic():
            # 创建事务保存点
            save_id = transaction.savepoint()
            while True:
                # 5.查询该房屋是否有订单冲突
                try:
                    count = Order.objects.filter(house_id=house_id, begin_date__lt=end_date, end_date__gt=start_date,
                                                 status=0).count()
                except Exception as e:
                    transaction.savepoint_rollback(save_id)
                    return JsonResponse({'errno': 4302,
                                         'errmsg': "读取失败"})
                if count > 0:
                    transaction.savepoint_rollback(save_id)
                    return JsonResponse({'errno': 4004,
                                         'errmsg': "该房屋已被预订"})
                # 查询SKU信息
                try:
                    order = Order.objects.create(user=user, house=house, begin_date=start_date, end_date=end_date, days=day,
                                                 house_price=house.price, amount=day*house.price)
                except Exception as e:
                    logger.error(e)
                    transaction.savepoint_rollback(save_id)
                    continue
                else:
                    # 7.返回结果
                    transaction.savepoint_commit(save_id)
                    return JsonResponse({'errno': 0,
                                         'errmsg':"ok",
                                         'data': {"order_id":order.id}})

    '''获取订单视图'''
    def get(self, request):
        """
        1. 去订单的表中查询当前登录用户下的订单
        2. 返回数据
        """
        user = request.user
        # 获取用户信息:房客：custom,房东：landlord
        role = request.GET.get("role")

        # 判断role是否是指定值
        if role not in ("custom", "landlord"):
            return JsonResponse({'errno': 4103,
                                 'errmsg': "参数错误"})
        if "custom" == role:
            # 房客订单查询
            try:
                orders = Order.objects.filter(user=user).order_by('-create_time')
                orders_dict_li = []
                for order in orders:
                    orders_dict_li.append({
                        "amount": order.amount,
                        "comment": order.comment,
                        "ctime": order.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                        "days": order.days,
                        "end_date": order.end_date.strftime("%Y-%m-%d"),
                        "img_url": order.house.index_image_url,
                        "order_id": order.id,
                        "start_date": order.begin_date.strftime("%Y-%m-%d"),
                        "status": order.ORDER_STATUS_ENUM[order.status],
                        "title": order.house.title
                    })
            except Exception as e:
                return JsonResponse({'errno': 4001,
                                     'errmsg': "生成订单失败"})
            # 7.返回结果
            return JsonResponse({'errno':"0",
                                     'errmsg': "ok",
                                     'data':{'orders':orders_dict_li}})
        try:
            houses = House.objects.filter(user=request.user)
            orders_dict_li = []
            for house in houses:
                orders = Order.objects.filter(house=house)
                for order in orders:
                    orders_dict_li.append({
                            "amount": order.amount,
                            "comment": order.comment,
                            "ctime": order.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                            "days": order.days,
                            "end_date": order.end_date.strftime("%Y-%m-%d"),
                            "img_url": order.house.index_image_url,
                            "order_id": order.id,
                            "start_date": order.begin_date.strftime("%Y-%m-%d"),
                            "status":order.ORDER_STATUS_ENUM[order.status],
                            "title": order.house.title
                        })
        except Exception as e:
            return JsonResponse({'errno': 4001,
                                     'errmsg': "生成订单失败"})
            # 7.返回结果
        return JsonResponse({'errno':0,
                                     'errmsg': "ok",
                                     'data':{'orders':orders_dict_li}})


# 接单和拒单
class OrdersStatusView(LoginRequiredMixin,View):
    def put(self, request, order_id):
        dict = json.loads(request.body)
        action = dict.get("action")
        reason = dict.get('reason')



        if not action:
            return JsonResponse({"errno":4002, 'errmsg': '缺少必传参数'})

        if action == 'accept':

            with transaction.atomic():
                # 创建事务保存点
                save_id = transaction.savepoint()
                try:
                    order = Order.objects.filter(id=order_id).update(status=1)
                    order_count = House.objects.get(id=order).order_count
                    House.objects.filter(id=order).update(order_count=order_count)
                except Exception as e:
                    transaction.savepoint_rollback(save_id)
                    return JsonResponse({'errno': 4001,
                                         'errmsg': "保存数据失败"})
                else:
                    transaction.savepoint_commit(save_id)
                    return JsonResponse({"errno": 0, 'errmsg': '房东已接单'})

        elif action == 'reject':  # 拒单
            try:
                Order.objects.filter(id=order_id).update(comment=reason,status=6)
            except Exception as e:
                return JsonResponse({'errno': 4001,
                                         'errmsg': "保存数据失败"})
            else:
                return JsonResponse({"errno": 0, 'errmsg': '拒单成功'})
        else:
            return JsonResponse({"errno":4103, 'errmsg': '参数错误'})


# 评论订单
class OrderCommentView(LoginRequiredMixin,View):

    def put(self,request,order_id):

        """
        订单评价
        1. 获取参数
        2. 校验参数
        3. 修改模型
        """
        # 1.获取参数
        data_json = json.loads(request.body.decode())
        order_id = order_id
        comment = data_json.get('comment')

        # 2.校验参数
        if not all([order_id,comment]):
            return JsonResponse({'errno': 4103,
                                 'errmsg': "参数错误"})

        try:
            order = Order.objects.get(user=request.user,id=order_id, status=3)
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4001,
                                 'errmsg': "该订单不存在"})
        # 3.修改模型并保存到数据库
        try:
            Order.objects.filter(user=request.user,id=order_id,status=3).update(comment=comment,status=4)
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4001,
                                 'errmsg': "保存数据失败"})















